package com.glory.hzlionpda.activity;

import android.Manifest;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hzlionpda.R;
import com.glory.hzlionpda.adapter.PopListAdapter;
import com.glory.hzlionpda.base.Constant;
import com.glory.hzlionpda.bean.BaseBean;
import com.glory.hzlionpda.utils.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_PasswordEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends FreeUI_BaseActivity implements EasyPermissions.PermissionCallbacks {


    public static final int RC_WRITE_AND_READ = 001;
    @BindView(R.id.tvVersion)
    TextView tvVersion;
    @BindView(R.id.ivBanner)
    ImageView ivBanner;
    @BindView(R.id.etMobile)
    FreeUI_ClearEditText etMobile;
    @BindView(R.id.etPassword)
    FreeUI_PasswordEditText etPassword;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.rlParent)
    RelativeLayout rlParent;
    @BindView(R.id.tvArea)
    TextView tvArea;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.flArea)
    FrameLayout flArea;
    private FreeUI_GeneralFragmentDialog freeUI_generalFragmentDialog, permissonDialog;
    private FreeUI_GeneralPop generalPop;
    private Animation animation, animationDismiss;
    private FreeUI_DownloadFragmentDialog dialog;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    etPassword.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData() {
        FreeApi_Utils.deleteLog();
        tvVersion.setText("V" + FreeApi_Utils.getVerName());
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
    }

    @OnClick({R.id.btnLogin, R.id.ivSetting, R.id.flArea})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                final String user = etMobile.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                if (user.length() == 0) {
                    showToast("请输入用户名", false);
                    return;
                }
                if (password.length() == 0) {
                    showToast("请输入密码", false);
                    return;
                }
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("USERNAME", user);
                    jsonObject.put("PASSWORD", password);
                    jsonObject.put("FABORG", tvArea.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                NetUtils.requestGetNet("USERLOGIN", this, jsonObject, new FreeUI_DialogEntityCallBack<BaseBean>(
                        new TypeToken<BaseBean>() {
                        }.getType(), getSupportFragmentManager(), this) {
                    @Override
                    public void onSuccess(Response<BaseBean> response) {
                        if (response.body().isSuccess(getApplicationContext())) {
                            showToast("登陆成功", true);
                            Constant.CURRENT_USER = user;
                            startActivity(new Intent(getApplicationContext(), HomeActivity.class));
                            LoginActivity.this.finish();
                        }
                    }

                    @Override
                    public void onError(Response<BaseBean> response) {
                        super.onError(response);
                        loadError(response.getException(), "USERLOGIN");
                    }
                });
                break;
            case R.id.ivSetting:
                freeUI_generalFragmentDialog = FreeApi_DialogUtils.getScanDialog(this, "请输入管理员密码", new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        freeUI_generalFragmentDialog.dismiss();
                        Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
                        intent.putExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY, "header");
                        startActivity(intent);
                    }
                });
                freeUI_generalFragmentDialog.show(getSupportFragmentManager(), "PASSWORD_VERIFY");
                break;
            case R.id.flArea:
                if (generalPop == null) {
                    View mView = LayoutInflater.from(this).inflate(R.layout.pop_choose_list, null);
                    RecyclerView recyclerView = mView.findViewById(R.id.rvList);
                    recyclerView.setLayoutManager(new LinearLayoutManager(this));
                    recyclerView.setItemAnimator(new DefaultItemAnimator());
                    recyclerView.addItemDecoration(new DividerItemDecoration(this, 1));
                    List<String> list = new ArrayList<>();
                    list.add("LION");
                    generalPop = new FreeUI_GeneralPop(this, mView
                            , flArea.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
                    final PopListAdapter popListAdapter = new PopListAdapter(list);
                    popListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    popListAdapter.isFirstOnly(true);
                    popListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                            tvArea.setText(String.valueOf(adapter.getItem(position)));
                            generalPop.dismiss();
                        }
                    });
                    recyclerView.setAdapter(popListAdapter);
                    generalPop.setOutsideTouchable(true);
                    generalPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            if (animationDismiss == null) {
                                animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                        0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                                animationDismiss.setDuration(500);
                                animationDismiss.setFillAfter(true);
                            }
                            ivArrow.startAnimation(animationDismiss);
                        }
                    });
                }
                showTypePop();
                break;
        }
    }

    private void showTypePop() {
        if (generalPop.isShowing()) {
            generalPop.dismiss();
        } else {
            if (animation == null) {
                animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                        0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setDuration(500);
                animation.setFillAfter(true);
            }
            ivArrow.startAnimation(animation);
            generalPop.showAsDropDown(flArea, 0, 0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (dialog == null) {
            if (android.os.Build.VERSION.SDK_INT >= 23) {
                requestMyPermissions();
            } else {
                requestUpdate();
            }
        }
    }

    @AfterPermissionGranted(RC_WRITE_AND_READ)
    private void requestMyPermissions() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "请授予权限，否则应用将无法正常使用",
                    RC_WRITE_AND_READ, perms);
        } else {
            requestUpdate();
        }
    }

    private void requestUpdate() {
        NetUtils.requestUpdate(new FreeUI_DialogEntityCallBack<FreeUI_VersionEntity>(
                new TypeToken<FreeUI_VersionEntity>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity versionEntity = response.body();
                if (Integer.parseInt(versionEntity.getVersion()) > Constant.VERSION_CODE) {
                    versionEntity.setApkName(getString(R.string.app_name));
                    versionEntity.setCurrentVersion(String.valueOf(Constant.VERSION_CODE));
                    dialog = new FreeUI_DownloadFragmentDialog();
                    dialog.setData(versionEntity);
                    dialog.show(getSupportFragmentManager(), "dialog_down_new");
                }
            }

            @Override
            public void onError(Response<FreeUI_VersionEntity> response) {
                super.onError(response);
                loadError(response.getException(), "requestUpdate");
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}

